var ds_id;
var ds_type;
var idStr;
var relation_id;
var user;
var lang;
var refresh;
var gid;
var ok_btn;
var cancel_btn;

var cacheNum=0;
var initCount=0;
var hasEdited = 0;//0--not edited,1--edited

var NOT_EDITED = 0;
var EDITED = 1;


String.prototype.trim=function(){
	return this.replace(/^\s*|\s*$/g, "");
};
$(document).ready(function(){
	ds_id = $("#ds_id").val();
	ds_type = $("#ds_type").val();
	idStr = $("#idStr").val();
	relation_id = $("#relation_id").val();
	user = $("#user").val();
	lang = $("#lang").val();
	refresh = $("#refresh").val();
	gid = $("#gid").val();
	if(lang == 'en'){
		ok_btn = "OK";
		cancel_btn = "Cancel";
	}else if(lang == 'zh'){
		ok_btn = "确定";
		cancel_btn = "取消";
	}
	var dtitle;
	if(lang == 'en'){
		dtitle = "On Loading";
	}else if(lang == 'zh'){
		dtitle = "正在加载";
	}
	$("#onloading").dialog({
		bgiframe : true,
		autoOpen : false,
		draggable : false,
		closeOnEscape : false,
		closeText : false,
		resizable : false,
		width : 400,
		title : dtitle,
		modal : true
	});
	$("#onloading").parent().appendTo("#dialog_target");
	$('a.ui-dialog-titlebar-close').hide();


	if (relation_id != "0" && refresh=="original") {//if saved at least once
		initialize(relation_id, ds_type, ds_id, idStr);//from db
	} else {//if come from relation_create_start.jsp first time
		initializeNew(relation_id);//from session
		hasEdited = EDITED;
	}
	$(".text_ipt").live("change",function(){
		$(this).removeClass("default");
		var newValue = $(this).val();
		var oldValue = $(this).defaultValue;
		var thId = "th#"+$(this).attr("id");
		$(thId).removeClass("normal");
		$(thId).removeClass("original");
		$(thId).addClass("highlight");
		var text = $(this).val();
		$(thId).find("span").text(text+" ("+$(this).attr("id")+")");
		if(text.trim().length>0){
			$(this).removeClass("error");
			$(this).parent().children(".errInfo").remove();
		}
		if($(this).hasClass("rel_name")){
			changeSessionName();
//			cacheRelation("changeName");
		}else{
			changeSessionRole();
//			cacheRelation("changeRole");//===========
		}
		hasEdited = EDITED;
	});//end of textipt_change
	$(".right .back").click(function(){
		var ctitle = "";
		var cmsg = "";
		if(lang == "en"){
			ctitle = 'Confirm';
			cmsg = 'You have edited on this relation, do you want to save changes before leave?';
		}else if(lang = "zh"){
			ctitle = '提示';
			cmsg = '您已对当前关系进行编辑，是否保存更改?';
		}
		if(hasEdited == EDITED){
			$.messager.confirm(ctitle,cmsg,function(r){  
			    if (r){  
			      if(saveClicked("go")){
			    	  if(ds_id>0){
							var location = "/sview/dataset/"+ds_type.charAt(0)+ds_id+"?openOp=relation";
							if(lang=="zh"){
								location += "&lang=zh";
							}
							window.location.href = location;
							window.location;
			    	  }else{
							var location = "/sview/dataset/"+ds_type.charAt(0)+idStr+"?openOp=relation";
							if(lang=="zh"){
								location += "&lang=zh";
							}
							window.location.href = location;
							window.location;
			    	  }
					}
			    }else{
					if(ds_id>0){
						var location = "/sview/dataset/"+ds_type.charAt(0)+ds_id+"?openOp=relation";
						if(lang=="zh"){
							location += "&lang=zh";
						}
						window.location.href = location;
						window.location;	
					}else{
						var location = "/sview/dataset/"+ds_type.charAt(0)+idStr+"?openOp=relation";
						if(lang=="zh"){
							location += "&lang=zh";
						}
						window.location.href = location;
						window.location;	
					}
			    } 
			
			});  
		}else{
			if(ds_id>0){
				var location = "/sview/dataset/"+ds_type.charAt(0)+ds_id+"?openOp=relation";
				if(lang=="zh"){
					location += "&lang=zh";
				}
				window.location.href = location;
				window.location;	
			}else{
				var location = "/sview/dataset/"+ds_type.charAt(0)+idStr+"?openOp=relation";
				if(lang=="zh"){
					location += "&lang=zh";
				}
				window.location.href = location;
				window.location;	
			}
		}
	});
	$("#save_btn").click(function(){
		saveClicked();
	});
	$("#back_btn").click(function(){
		if(cacheNum==1){
			alert("Nothing to cancel");
		}else{
			getCache();
		}
	});
	$(".expander").live("click", function(){
		var v = $(this).text();
		var vOperateDiv = prepareVOperateDiv(v, relation_id, ds_id, ds_type, idStr);//=========
//		var num = $(expandDiv).attr("num");
		var h = 500;//(num * 20)+100;
		$(vOperateDiv).dialog({
			modal: true,
			minWidth: 450,
			height: h,
			top: 150,
			buttons:[{
				text: ok_btn,
				click: function(){
					var triple = $("input[name=expandRadio]:checked").parent().parent();
					if(triple==undefined){
						if(lang == 'en'){
							alert("Please select a pattern to expand, or click cancel.");
						}else if(lang == 'zh'){
							alert("请选择要扩展的模式，或点击取消");
						}
					}else{
						var data = {};
						var s = $(triple).attr("s");
						var p = $(triple).attr("p");
						var o = $(triple).attr("o");
//						alert(s+"|"+p+"|"+o);
						data["s"] = s;
						data["p"] = p;
						data["o"] = o;
						data["id"] = relation_id+"";
						data["ds_type"] = ds_type;
						data["ds_id"] = ds_id;
						data["idStr"] = idStr;
						data = JSON.stringify(data);
						data = ("data="+encodeURIComponent(data));
						$.ajax({
							url: "/sview/expandAdd",
							async: true,
							data: data,
							dataType: 'json',
							type: 'post',
							success: function(result){
								if(result["err"] == "err"){
									if(lang == 'en'){
										alert("Failed, please try latter.");
									}else if(lang == 'zh'){
										alert("操作失败，请稍后再试");
									}
								}else{
									hasEdited = EDITED;
//									var curNum = initCount;
									getRelRoles(relation_id);//init+1
//									getPattern(relation_id);//init+1
									getRule(relation_id);
									getResult(relation_id, ds_type, ds_id,idStr);
									$(vOperateDiv).dialog("close");
//									cacheRelation("expand", s, p, o);
									
//									alert(initCount+"|"+curNum);
//									while(initCount-curNum<2){
////										alert("in:"+(initCount-curNum));
//										//=====================
//									}
//									alert("out:"+(initCount-curNum));
//									var url = "relation_edit.jsp?relation_id="+relation_id
//										+"&ds_type="+ds_type
//										+"&ds_id="+ds_id
//										+"&lang="+lang
//										+"&refresh=refresh";//from session,must be the last param
//									window.location = url;
								}
							}
						});
						
					}
				}
			},{
				text: cancel_btn,
				click: function(){
					$(vOperateDiv).dialog("close");
				}
			}]
		});//end of dialog
	});
	$(".del").live("click", function() {
		var s = $(this).parent().attr("s");
		var p = $(this).parent().attr("p");
		var o = $(this).parent().attr("o"); 
//		cacheRelation("tripleDel",s,p,o);
		var data = {};
		data["s"] = s;
		data["p"] = p;
		data["o"] = o;
		data["rel_id"] = relation_id;
		data = JSON.stringify(data);
		data = ("data=" + encodeURIComponent(data));
		$.ajax({
			url : "/sview/tripleDel",
			async : true,
			data : data,
			dataType : "json",
			type : "post",
			success : function(result) {
				hasEdited = EDITED;
				getRelRoles(relation_id);
//				getPattern(relation_id);
				getRule(relation_id);
				getResult(relation_id, ds_type, ds_id, idStr);
//				cacheRelation("tripleDel", s, p, o);
				hasEdited = EDITED;
			}
		});
	});
	$(".optab").live("click", function(){
		var old = $(this).siblings(".active");
		var v  = $("#vOperateDiv").attr("v");
		if(old.length>0){
			$(old).removeClass("active");
			$(this).addClass("active");
			showDiv($(this),v, relation_id, ds_id, ds_type, idStr);
		}
	});

})//end of ready
function initialize(relation_id, ds_type, ds_id, idStr) {
	var data = {};
	data["id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationIntoSession",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			getRelationName(relation_id);
			getRelRoles(relation_id);
//			getPattern(relation_id);
			getRule(relation_id);
			getResult(relation_id, ds_type, ds_id, idStr);
		}
	});
}

function initializeNew(relation_id){//id=0
	getRelationName(relation_id);
	getRelRoles(relation_id);
//	getPattern(relation_id);

	getRule(relation_id);
	getResult(relation_id, ds_type, ds_id, idStr);
}

function initUlCache(str){
	if(initCount<2){
		initCount++;
	}else if(initCount==2){
		var currUlId = "#panel"+cacheNum;
		var currUl = $(currUlId);
		var oldUl = $(currUl).clone();
		$(oldUl).removeClass("currUl");
		$(oldUl).attr("action","init");
		cacheNum++;
		$(currUl).attr("id", "panel"+cacheNum);
		$(currUl).parent().append($(oldUl));
		$(oldUl).find(".errInfo").remove();//=====
		$(oldUl).hide();
		initCount++;
//		alert($(".currUl #rel_name_input").val()+"|"+$(".currUl #role_sel input[type='checkbox']").length);
	}else{
		initCount++;
	}
//	alert(str+"|init:"+initCount+"|"+(initCount<2));
}
function cacheRelation(action,s,p,o){
	var oldUlId = "#panel"+cacheNum;
	var oldUl = $(oldUlId);
	var ul = $(oldUlId).clone();
	$(ul).attr("action",action);
	$(ul).removeClass("currUl");
	
	if(action=="expand" || action=="tripleDel"){
		$(ul).attr("s",s);
		$(ul).attr("p",p);
		$(ul).attr("o",o);
	}
	if($(ul).length>0){
		$(oldUl).parent().append($(ul));
		$(ul).find(".errInfo").remove();//=====
		$(ul).hide();
		cacheNum++;
		$(oldUl).attr("id","panel"+cacheNum);
		
		$("#ruleName:visible").text($("#rel_name_input").val()+"(");//==for change pattern head
	}
}
function getCache(){
	var currUlId = "#panel"+cacheNum;
	var currUl = $(currUlId);
	var currAct = $(currUl).attr("action");
	
	$(currUl).remove();
	cacheNum = cacheNum-1;
	var sameUlId = "#panel"+cacheNum;
	var sameUl = $(sameUlId);
	setSession($(sameUl));
	$(sameUl).remove();
	
	cacheNum = cacheNum-1;
	var oldUlId = "#panel"+cacheNum;
	if($(oldUlId).length>0){
		var oldUl = $(oldUlId);
		cacheNum++;
		var copyUl = $(oldUl).clone();//copy version for show
		$(copyUl).attr("id","panel"+cacheNum);
		$(copyUl).addClass("currUl");
		$(copyUl).removeAttr("action");
		
		$(oldUl).parent().append($(copyUl));
		$(copyUl).show();
		
//		cacheRelation($(oldUl).attr("action"),$(oldUl).attr("s"),$(oldUl).attr("p"),$(oldUl).attr("o"));
//		setSession($(oldUl));
//		if(cacheNum==0){
//			var currUlId = "#panel"+cacheNum;
//			var currUl2 = $(currUlId);
//			var oldUl = $(currUl2).clone();
//			$(oldUl).removeClass("currUl");
//			cacheNum++;
//			$(currUl2).attr("id", "panel"+cacheNum);
//			$(currUl2).parent().append($(oldUl));
//		}
	}else{
		alert("Nothing to cancel");
	}
}
function setSession(ul){
	var action = $(ul).attr("action");
	if(action == "changeName"){
		changeSessionName();
	}else if(action == "changeRole"){
		changeSessionRole();
	}else if(action == "expand"){
		removeSessionPattern($(ul));
	}else if(action == "tripleDel"){
		addSessionPattern($(ul));
	}else if(action == "init"){
		if(relation_id == 0){
			initializeNew(relation_id);//from session
		}else{
			initialize(relation_id, ds_type, ds_id, idStr);//from db
		}
	}
}
	
function changeSessionName(){
	var data = {};
	data["id"] = relation_id;
	data["name"] = $(".currUl #rel_name_input").val();
	data = JSON.stringify(data);
	data = ("changeName=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/changeRoles",
		async : false,/*true,*/
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
//			alert("changeName:"+result["result"]);
		}
	});	
}
function changeSessionRole(){
	var sels = new Array();
	$(".currUl #role_sel input[type='checkbox']").each(
			function() {
				if ($(this).attr("checked") == "checked") {
					var ipt = $(this).parent().children("input[type='text']");
					var a = $(ipt).attr("value");
					var v = $(this).attr("name");
					var item = new Object();
					item["v"] = v;
					item["role"] = a;
					sels.push(item);
				}
	});
	var data = {};
	data["id"] = relation_id;
	data["roles"] = sels;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/changeRoles",
		async : false,/*true,*/
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
//			alert("changeRole:"+result["result"]);
		}
	});
}
function removeSessionPattern(ul){
	var s = $(ul).attr("s");
	var p = $(ul).attr("p");
	var o = $(ul).attr("o");
	var data = {};
	data["s"] = s;
	data["p"] = p;
	data["o"] = o;
	data["rel_id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/tripleDel",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
//			alert("removePattern:"+result["result"]);
			getRelRoles(relation_id);
//			getPattern(relation_id);
			getRule(relation_id);
			getResult(relation_id, ds_type, ds_id,idStr);
		}
	});
}
function addSessionPattern(ul){
	var data = {};
	data["s"] = $(ul).attr("s");
	data["p"] = $(ul).attr("p");
	data["o"] = $(ul).attr("o");
	data["id"] = relation_id+"";
	data["ds_type"] = ds_type;
	data["ds_id"] = ds_id;
	data["idStr"] = idStr;
	data = JSON.stringify(data);
	data = ("data="+encodeURIComponent(data));
	$.ajax({
		url: "/sview/expandAdd",
		async: true,
		data: data,
		dataType: 'json',
		type: 'post',
		success: function(result){
//			alert("addPattern:"+result["result"]);
			getRelRoles(relation_id);
//			getPattern(relation_id);
			getRule(relation_id);
			getResult(relation_id, ds_type, ds_id, idStr);
		}
	});
}
function showDiv(tab,v, relation_id, ds_id, ds_type, idStr){
	var divName = "#"+$(tab).attr("id").replace("Tab","Div");
	if($(divName).hasClass("origin")){
		var operate = $(tab).attr("id").replace("Tab","")
		if(operate=="expand"){
			expand(v, relation_id, ds_id, ds_type, idStr);
			$(divName).removeClass("origin");
		}else if(operate=="restrict"){
			restrict(v, relation_id, ds_id, ds_type, idStr);
			$(divName).removeClass("origin");
		}else if(operate=="bind"){
			bind(v, relation_id, ds_id, ds_type, idStr);
			$(divName).removeClass("origin");
		}else{
			alert("no corresponding function!");
		}
	}
	$(divName).show();
	$(divName).siblings(".panel").hide();
}

function prepareVOperateDiv(v, relation_id, ds_id, ds_type, idStr){
	var act = $("#vOperateDiv li.active");
	if($(act).attr("id")=="expandTab"){
		expand(v, relation_id, ds_id, ds_type, idStr);
	}else if($(act).attr("id")=="restrictTab"){
		restrict(v, relation_id, ds_id, ds_type, idStr);
	}else if($(act).attr("id")=="bindTab"){
		bind(v, relation_id, ds_id, ds_type, idStr);
	}else{
		alert("error! activeId="+$(act).attr("id"));
	}
	var div = "#"+($(act).attr("id").replace("Tab","Div"));
	$(div).siblings().addClass("origin");
//	$("#expandDiv").siblings().addClass("origin");
	$("#vOperateDiv").attr("v",v);
	return $("#vOperateDiv");
	/*var data={};
	data["v"] = v;
	data["relation_id"] = relation_id+"";
	data["ds_id"] = ds_id+"";
	data["ds_type"] = ds_type;
	data = JSON.stringify(data);
	data = ("vInfoCheck="+encodeURIComponent(data));
	$.ajax({
		url: "/sview/relationExpand",//====
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		
		success:function(result){
			var canExpand = result["canExpand"];
			var canRestrict = result["canRestrict"];
			var canBind = result["canBind"];
			if((eval(canExpand)) == false) && (eval(canExpand)) == false) && eval(canExpand)) == false){
				$(".optab").hide();
				$(".opdiv").hide();
				var infoDiv = $("#infoDiv");
				var span = $("<span></span>");
				if(lang == "en"){
					$(span).text("Nothing for operations on this variable in current dataset.");
				}else if(lang=="zh"){
					$(span).text("当前数据集不支持对此变量的任何操作。");
				}
				infoDiv.html(span);
				infoDiv.show();
				return;
			}
			if(eval(canExpand)) == true){
				$("#expandTab").show();
				expand(v, relation_id, ds_id, ds_type);
			}else{
				$("#expandTab").hide();
				$("#expandDiv").hide();
				if(eval(canRestrict) == true){
					restrict(v, relation_id, ds_id, ds_type);
				}else{
					$("#restrictTab").hide();
					$("#restrictDiv").hide();
					bind(v, relation_id, ds_id, ds_type);
				}
			}
			if(eval(canRestrict) == true){
				$("#restrictTab").show();
			}else{
				$("#restrictTab").hide();
			}
			if(eval(canBind)) == true){
				$("#bindTab").show();
			}else{
				$("#bindTab").hide();
			}
		}
	});*/
}

function expand(v, relation_id, ds_id, ds_type, idStr){
	$("#panels").addClass("loading2");
	var data={};
	data["vars"] = v;
	data["id"] = relation_id+"";
	data["ds_id"] = ds_id+"";
	data["ds_type"] = ds_type;
	data["idStr"] = idStr;
	data = JSON.stringify(data);
	data = ("data="+encodeURIComponent(data));
//	$("#onloading").dialog("open");
	$.ajax({
		url: "/sview/relationExpand",
		async : false,/*true,*/
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
//			$("#onloading").dialog("close");
			$("#panels").removeClass("loading2");
			var lang = $("#lang").val();
			var array = result["result"];
			$("#expandDiv").html("");
			if(array.length==0){
				var note = $("<div class='note'></div>");
				if(lang == "en"){
					note.text("No availiable pattern in current dataset.");
				}else{
					note.text("当前数据集无可用模式。")
				}
				$("#expandDiv").append(note);
				
			}else{
				$("#expandDiv").remove(".note");
			}
			for ( var i = 0; i < array.length; i++) {
				var triple = array[i];
				var stext = new String(triple["stext"]);
				var ptext = new String(triple["ptext"]);
				var otext = new String(triple["otext"]);
				var s = new String(triple["s"]);
				var p = triple["p"];
				var o = new String(triple["o"]);
				var s_dis = stext;
				var p_dis = ptext;
				var o_dis = otext;
				if (s.indexOf("u") == 0) {
					s_dis = getLocalname(stext);
				}
				p_dis = getLocalname(ptext);
				if (o.indexOf("u") == 0) {
					o_dis = getLocalname(otext);
				}
				var tripleDIV = $("<div class='triple'></div>");
				tripleDIV.attr("s", s);
				tripleDIV.attr("p", p);
				tripleDIV.attr("o", o);
				$("#expandDiv").append(tripleDIV);
				var disDIV = $("<span></span>");
				var radio = $("<input name='expandRadio' type='radio' />");
				$(disDIV).append(radio);
				disDIV.append("(<span title='" + stext + "'>" + s_dis
						+ "</span>,<span title='" + ptext + "'>"
						+ p_dis + "</span>,<span title='" + otext
						+ "'>" + o_dis + "</span>)");
				tripleDIV.append(disDIV);
			}
		}
	});
}
function restrict(v, relation_id, ds_id, ds_type, idStr){
	$("#panels").addClass("loading2");
	var data={};
	data["v"] = v;
	data["id"] = relation_id+"";
	data["ds_id"] = ds_id+"";
	data["ds_type"] = ds_type;
	data["idStr"] = idStr;
	data = JSON.stringify(data);
	data = ("restrict="+encodeURIComponent(data));
//	$("#onloading").dialog("open");
	$.ajax({
		url: "/sview/relationExpand",
		async : false,/*true,*/
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#panels").removeClass("loading2");
//			$("#onloading").dialog("close");
			var lang = $("#lang").val();
			var array = result["result"];
			$("#restrictDiv").html("");
			if(array.length==0){
				var note = $("<div class='note'></div>");
				if(lang == "en"){
					note.text("No availiable pattern in current dataset.");
				}else{
					note.text("当前数据集无可用模式。")
				}
				$("#restrictDiv").append(note);
			}
			for ( var i = 0; i < array.length; i++) {
				var triple = array[i];
				var stext = new String(triple["stext"]);
				var ptext = new String(triple["ptext"]);
				var otext = new String(triple["otext"]);
				var s = new String(triple["s"]);
				var p = triple["p"];
				var o = new String(triple["o"]);
				var s_dis = stext;
				var p_dis = ptext;
				var o_dis = otext;
				if (s.indexOf("u") == 0) {
					s_dis = getLocalname(stext);
				}
				p_dis = getLocalname(ptext);
				if (o.indexOf("u") == 0) {
					o_dis = getLocalname(otext);
				}
				var tripleDIV = $("<div class='triple'></div>");
				tripleDIV.attr("s", s);
				tripleDIV.attr("p", p);
				tripleDIV.attr("o", o);
				$("#restrictDiv").append(tripleDIV);
				var disDIV = $("<span></span>");
				var radio = $("<input name='expandRadio' type='radio' />");
				$(disDIV).append(radio);
				disDIV.append("(<span title='" + stext + "'>" + s_dis
						+ "</span>,<span title='" + ptext + "'>"
						+ p_dis + "</span>,<span title='" + otext
						+ "'>" + o_dis + "</span>)");
				tripleDIV.append(disDIV);
			}
		}
	});
}
function bind(v, relation_id, ds_id, ds_type,idStr){//=====to be completed======
	$("#bindDiv").html("");
	var note = $("<div class='note'></div>");
	if(lang == "en"){
		note.text("This function haven't completed yet.");
	}else{
		note.text("此功能尚未提供。")
	}
	$("#bindDiv").append(note);
}
function saveClicked(go){
	var saved = false;
	var sels = new Array();
	if($(".errInfo").length>0) return false;
	$(".currUl #role_sel input[type='checkbox']").each(
			function() {
				if ($(this).attr("checked") == "checked") {
					var ipt = $(this).parent().children("input[type='text']");
					var a = $(ipt).attr("value");
					var v = $(this).attr("name");
					var item = new Object();
					item["v"] = v;
					item["role"] = a;
					sels.push(item);
					if(checkRoleValue(item) == false){
						$(ipt).addClass("error");
						var espan = $("<span class='errInfo'></span>");
						if(lang=="en"){
//							espan.text("Please input role name of the selected variable.");
							espan.text("Please input name of the selected variable.");
						}else if(lang=="zh"){
							espan.text("请输入所选变量的角色名。");
						}
						ipt.after(espan);
					}
				}
			});
	checkRelName($(".currUl #rel_name_input"));
	if($(".errInfo").length>0) return false;
	if (checkRoles(sels) == true) {
		var name = $(".currUl #rel_name_input").val();
		saved = save(relation_id, sels, name, user);
		if(saved && (go==null)){
			if (relation_id != 0) {
				window.location.reload();
			} else {
				relation_id = result["rel_id"];
				url = window.location.href.replace(/relation_id=\d+/, "relation_id="+relation_id);
				window.location = url;
			}
		}else if(go=="go"){
			return saved;
		}
	} 
	return saved;
}//end of save
function checkRoleValue(item){
	var role = item["role"];
	if(role.trim().length==0){
		return false;
	}
	return true;
}
function checkRoles(sels) {
	if (sels.length == 0)
		return false;
	var ret = true;
	for (var i=0; i<sels.length; i++) {
		var role = sels[i]["role"];
		role = role.trim();
		if (role == "") {
			ret = false;
		}
	}
	return ret;
}
function checkRelName(nameIpt) {
	var name = $(nameIpt).val();
	var ret = true;
	if (name.trim() == "") {
		$(nameIpt).addClass("error");
		var espan = $("<span class='errInfo'></span>");
		if(lang=="en"){
			espan.text("Please input relation name.");
		}else if(lang=="zh"){
			espan.text("请输入所选变量的角色名！");
		}
		nameIpt.after(espan);
		ret = false;
	}
	var data={};
	data["rel_id"] = relation_id;
	data["name"]=name;
	data["groupID"]=gid;
	data = JSON.stringify(data);
	data = ("checkRelNameConflict=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationInfo",
		async : false,/*true,*/
		data : data,
		dataType : "text",
		type : "post",
		success : function(result) {
			if(result=="conflict" || result=="ask"){
//				alert("Name conflict in current group!");
				$(nameIpt).addClass("error");
				var espan = $("<span class='errInfo'></span>");
				if(lang=="en"){
					espan.text("Name conflict in current group!");
				}else if(lang=="zh"){
					espan.text("当前编辑组内已有同名关系");
				}
				$(nameIpt).after(espan);
//				ret = false;
//				return false;
			}else{
//				ret = true;
//				return true;
			}
		}
	});
}
function save(relation_id, sels, name, user) {
	var data = {};
	data["id"] = relation_id;
	data["roles"] = sels;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	var rt = $.ajax({
		url : "/sview/changeRoles",
		async : false,//true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var data = {};
			data["id"] = relation_id;
			data["name"] = name;
			data["user"] = user;
			data["ds_id"] = ds_id+"";
			data["ds_type"] = ds_type;
//			data["gid"] = $("#gid").val();
			data = JSON.stringify(data);
			data = ("info=" + encodeURIComponent(data));
			$.ajax({
				url : "/sview/saveRelation",
				async : true,
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var rs = result["result"];
					if(rs=="OK"){
						if(lang == 'en'){
							alert("Saved.");
						}else if(lang == 'zh'){
							alert("已保存。");
						}
//						if (relation_id != 0) {
//							window.location.reload();
//						} else {
//							relation_id = result["rel_id"];
//							url = window.location.href.replace(/relation_id=\d+/, "relation_id="+relation_id);
//							window.location = url;
//						}
						hasEdited = NOT_EDITED;
						return true;
					}else if(rs == "nogroup"){
						if(lang == 'en'){
							alert("Failed! Please set an editing group!");
						}else if(lang == 'zh'){
							alert("操作失败: 未确定编辑组。");
						}
						return false;
//						alert("Failed! Session has timed out!")
					}
				}
			});
		}
	});
	return rt;
}
function getRelRoles(relation_id) {
	var data = {};
	data["id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationRoles",
		async : false,//true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$(".currUl #role_sel").html("");
			var array = result["result"];
			var new_rel = (relation_id == 0);//infer whether a new relation
			for ( var i = 0; i < array.length; i++) {
				var v_role = array[i];
				var v = v_role["v"];
				var role = v_role["role"];
//				var div = $("<div class='role'></div>");
				var div = $("<li class='role'></li>");
				$(".currUl #role_sel").append(div);
				var ckbox = $("<input class='roleCheck' type='checkbox'></input>");
				ckbox.attr("name", v);
				ckbox.attr("id",i);
				if (new_rel || role != "") {
					ckbox.attr("checked", "checked");
//				}else{
//					$("#resultTable").flexToggleCol(i,false);
				}
				div.append(ckbox);
				var span = $("<span></span>");
				span.html(v);
				div.append(span);
				var input = $("<input type='text' class='input-medium text_ipt'></input>");
				input.attr("value", role);
				if(role==null || role==""){
					input.attr("value", "name_of_"+v);
//					input.attr("placeholder","name_of_"+v);
					input.addClass("default");//===========
				}
				input.attr("id",v);
				div.append(input);
			}
		$(".roleCheck").change(function(){
			var id = $(this).attr("id");
			var newRV = $("#rv"+id);//==for change pattern head
			if($(this).attr("checked") == "checked"){
				$("#resultTable").flexToggleCol(id,true);
				//change pattern head
				var oldLast = $(".lastV:visible");
				if($(oldLast).length>0 && $(oldLast).attr("id").substr(2)<id){
					var oldText = $(oldLast).text()+"";
					$(oldLast).text(oldText+",");
					$(oldLast).removeClass("lastV");
					
					var txt = $(newRV).text()+"";
					$(newRV).text(txt.substring(0,txt.length-1));
					$(newRV).addClass("lastV");
				}
				$(newRV).css("display","inline");
			}else{
				$("#resultTable").flexToggleCol(id,false);
				//change pattern head
				$(newRV).hide();
				if($(newRV).hasClass("lastV")){
					var oldText = $(newRV).text()+"";
					$(newRV).text(oldText+",");
					$(newRV).removeClass("lastV");
					
					var lastV = $(".ruleV:visible").last();
					var oldText = $(lastV).text()+"";
					$(lastV).text(oldText.substring(0,oldText.length-1));
					$(lastV).addClass("lastV");
				}
			}
		});//end of roleCheck_change
		initUlCache("role");//=============
		}//end of success
	});//end of ajax
}

function getRelationName(relation_id) {
	var data = {};
	data["id"] = relation_id+"";
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationInfo",
		async : false,/*true,*/
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var name = result["name"];
			$(".currUl #rel_name_input").attr("value", name);
			if(name.length<1){
				$(".currUl #rel_name_input").attr("value", "undefined");
			}
			initUlCache("name");//=============
		}
	});
}
function getRule(relation_id){
	var data = {};
	data["id"] = relation_id+"";
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
				url : "/sview/relationRule",
				async : false,/*true,*/
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var head = result["head"];
					var array = result["elements"];
					var showText;
					var lang = $("#lang").val();
//					if(lang == 'en'){
//						showText = "reset";
//					}else if(lang == 'zh'){
//						showText = "重置";
//					}
//					$("#pattern_left").html("<div id='pattern_reset'><input type='button' class='button-bg' value='"+showText+"' id='reset'></input></div>");
					$("#reset_btn").click(function() {
						var url = window.location.href.replace(/&refresh=\w+/, "");
//						location.reload();
						window.location = url;
					});
					$("#cancel_btn").click(function() {
						if(ds_id>0){
							var location = "/sview/dataset/"+ds_type.charAt(0)+ds_id+"?openOp=relation";
							if(lang=="zh"){
								location += "&lang=zh";
							}
							window.location=location;
						}else{
							var location = "/sview/dataset/"+ds_type.charAt(0)+idStr+"?openOp=relation";
							if(lang=="zh"){
								location += "&lang=zh";
							}
							window.location=location;
						}
//						var url = window.location.href.replace(/&refresh=\w+/, "");
////						location.reload();
//						window.location = url;
					});
					var patternUl = $(".currUl #patterns");
					patternUl.html("");
					var headSpan = $("<span class='ruleHead'></span>");
					var rnameSpan = $("<span id='ruleName'></span>");
					rnameSpan.text($("#rel_name_input").val()+"(");
					$(headSpan).append(rnameSpan);
					var rvaluesSpan = $("<span id='ruleValues'></span>");
//					$(rvaluesSpan).text(head);
					for(var i=0; i<head.length; i++){
						var v = head[i];
						var vSpan = $("<span class='ruleV'></span>");
						$(vSpan).attr("id","rv"+i);
						$(vSpan).text(v["v"]+",");
						if(v["show"] == 1){
							$(vSpan).show();
						}else{
							$(vSpan).hide();
						}
						$(rvaluesSpan).append(vSpan);
					}
					$(headSpan).append(rvaluesSpan);
					var signSpan = $("<span id='ruleSign'></span>");
					$(signSpan).text(") :-");
					$(headSpan).append(signSpan);
					
					patternUl.append(headSpan);
					//remove last ","
					var lastV = $(".ruleV:visible").last();
					var oldText = $(lastV).text()+"";
					$(lastV).text(oldText.substring(0,oldText.length-1));
					$(lastV).addClass("lastV");
					
					
					for ( var i = 0; i < array.length; i++) {
						var triple = array[i];
						var ptext = new String(triple["ptext"]);
						var vtext = triple["vtext"];
//						alert(vtext.length+"|"+vtext[0]+"|"+vtext[1]);
						var s = new String(triple["s"]);
						var p = triple["p"];
						var o = new String(triple["o"]);
						var p_dis = ptext;
						var v_dis = vtext;
						var html_v="";
						p_dis = getLocalname(ptext);
						for(var j=0; j<vtext.length; j++){
							var txt = vtext[j];
							if(txt.indexOf("u") == 0){
								v_dis = getLocalname(vtext[j]);
							}
							if(txt.charAt(0) == "v"){
								v_dis = "<a class='expander' href='javascript:void(0);'>"+txt+"</a>";
							}
//							alert(i+"|"+v_dis);
							if(j==1){
								html_v += ",";
							}
							html_v += "<span title='" + txt + "'>" + v_dis+ "</span>"
						}
						var canDel = triple["canDel"];
//						var tripleDIV = $("<div class='triple'></div>");
						var triple = $("<li class='triple'></li>")
						triple.attr("s", s);
						triple.attr("p", p);
						triple.attr("o", o);
						$(patternUl).append(triple);
						var disDIV = $("<span></span>");
//						disDIV.html("(");
//						var sSpan = $("<span></span>");
//						$(sSpan).attr("title",stext);
//						$(sSpan).append(s_dis);
//						alert($(sSpan).text());
//						disDIV.append(sSpan);
						if(i<array.length-1){
							disDIV.html("<span title='" + ptext + "'>"
									+ p_dis + "</span>(" + html_v + "),");
						}else{
							disDIV.html("<span title='" + ptext + "'>"
									+ p_dis + "</span>(" + html_v + ").");
						}
						triple.append(disDIV);
						if (eval(canDel) == true) {
							var delDIV = $("<a class='del' href='javascript:void(0)'><img src='/sview/icons/edit_cancel.png' border='0'/></a>");
							triple.append(delDIV);
						}
					}
					initUlCache("pattern");//=============
				}
			});
}
function getPattern(relation_id) {
	var data = {};
	data["id"] = relation_id+"";
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
				url : "/sview/relationPattern",
				async : false,/*true,*/
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var array = result["result"];
					var showText;
					var lang = $("#lang").val();
//					if(lang == 'en'){
//						showText = "reset";
//					}else if(lang == 'zh'){
//						showText = "重置";
//					}
//					$("#pattern_left").html("<div id='pattern_reset'><input type='button' class='button-bg' value='"+showText+"' id='reset'></input></div>");
					$("#reset_btn").click(function() {
						var url = window.location.href.replace(/&refresh=\w+/, "");
//						location.reload();
						window.location = url;
					});
					var patternUl = $(".currUl #patterns");
					patternUl.html("");
					for ( var i = 0; i < array.length; i++) {
						var triple = array[i];
						var stext = new String(triple["stext"]);
						var ptext = new String(triple["ptext"]);
						var otext = new String(triple["otext"]);
						var s = new String(triple["s"]);
						var p = triple["p"];
						var o = new String(triple["o"]);
						var s_dis = stext;
						var p_dis = ptext;
						var o_dis = otext;
						if (s.indexOf("u") == 0) {
							s_dis = getLocalname(stext);
						}
						p_dis = getLocalname(ptext);
						if (o.indexOf("u") == 0) {
							o_dis = getLocalname(otext);
						}
						var canDel = triple["canDel"];
//						var tripleDIV = $("<div class='triple'></div>");
						var triple = $("<li class='triple'></li>")
						triple.attr("s", s);
						triple.attr("p", p);
						triple.attr("o", o);
						$(patternUl).append(triple);
						var disDIV = $("<span></span>");
//						disDIV.html("(");
//						var sSpan = $("<span></span>");
//						$(sSpan).attr("title",stext);
//						$(sSpan).append(s_dis);
//						alert($(sSpan).text());
//						disDIV.append(sSpan);
						
						if(stext.charAt(0)=="v"){
							s_dis = "<a class='expander' href='javascript:void(0);'>"+s_dis+"</a>";
						}
						if(otext.charAt(0)=="v"){
							o_dis = "<a class='expander' href='javascript:void(0);'>"+o_dis+"</a>";
						}
						
						disDIV.html("(<span title='" + stext + "'>" + s_dis
								+ "</span>,<span title='" + ptext + "'>"
								+ p_dis + "</span>,<span title='" + otext
								+ "'>" + o_dis + "</span>)");
						triple.append(disDIV);
						if (eval(canDel) == true) {
							var delDIV = $("<a class='del' href='javascript:void(0)'><img src='/sview/icons/edit_cancel.png' border='0'/></a>");
							triple.append(delDIV);
						}
					}
					initUlCache("pattern");//=============
				}
			});
}
function getResult(relation_id, ds_type, ds_id,idStr) {
	var data = {};
	data["id"] = relation_id+"";
	data["ds_type"] = ds_type;
	data["ds_id"] = ds_id+"";
	data["idStr"] = idStr;
	data["dis_all"] = "all";
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$("#edit_result").addClass("loading2");
//	$("#onloading").dialog("open");
	$.ajax({
				url : "/sview/relationResult",
				async : true,
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					$("#edit_result").removeClass("loading2");
					var lang = $("#lang").val();
//					$("#onloading").dialog("close");
					var showText;
					if(lang == 'en'){
						showText = "expand";
					}else if(lang == 'zh'){
						showText = "扩展";
					}
					var expandaa = $("<input type='button' class='button-bg' value='"+showText+"' id='expand'></input>");
					expandaa.hide();
					$("#edit_result").html(expandaa);
					var table = $("<table id='resultTable'></table>");
					$("#edit_result").append(table);
					var array = result["result"];
					var tableTitle = array[0];
					var thead = $("<thead></thead>");
					table.append(thead);
					var trhead = $("<tr></tr>");
					thead.append(trhead);
					for ( var i = 0; i < tableTitle.length; i++) {
						var column = tableTitle[i];
						var v = column["v"];
						var th = $("<th width='100'></th>");
						$(th).attr("id",v);
						var span = $("<span></span>");
						
						var ckboxId = "#"+i;
						if($(ckboxId).attr("checked")=="checked"){
							var inpId = "#"+v;
							if($(inpId).val().trim().length>0){
								span.text($(inpId).val()+" ("+v+")");
								th.append(span);
								th.addClass("normal");
							}else{
								span.text(v);
								th.append(span);
								th.addClass("original");
							}
						}else{
							span.text(v);
							th.append(span);
							th.addClass("original");
						}
//						span.text(v);
//						th.append(span);
						
//						var ckbox = $("<input type='checkbox' class='checkInput' name='"+showText+"'></input>");
//						ckbox.hide();
//						ckbox.attr("value", v);
//						th.prepend(ckbox);
						trhead.append(th);
					}
					var tbody = $("<tbody></tbody>");
					table.append(tbody);
					for ( var i = 1; i < array.length; i++) {
						var trbody = $("<tr></tr>");
						tbody.append(trbody);
						var item = array[i];
						for ( var j = 0; j < item.length; j++) {
							var ele = item[j];
							var v = ele["v"];
							var name = new String(ele["name"]);
							var content = ele["content"];
							var dis = ele["displayName"].trim();
							if(dis.length==0){
								dis = content;
							}
//							alert("dis:"+dis);
//							var dis = content;
//							if (name.indexOf("u") == 0) {
//								dis = getLocalname(content);
//							}
							var td = $("<td></td>");
							trbody.append(td);
							td.attr("v", v);
							td.attr("name", name);
							var div = $("<span></span>");
							var uri_id = ele["uri_id"];
							if(ele["uri_id"] != null){
								var a = $("<a></a>");
								var href = "/sview/entity/o"+uri_id;
								$(a).attr("href",href);
								$(a).attr("title", content);
								$(a).text(dis);
								div.append(a);
							}else{
								div.attr("title", content);
								div.text(dis);
							}
							td.append(div);
						}
					}
//					alert($(table).html());
					$("#resultTable").flexigrid({
						showcheckbox: false,
						height: 400,
						showToggleBtn:false
					});
					//only show checked column
					$(".roleCheck").each(function(){
						if($(this).attr("checked") != "checked"){
							var id = $(this).attr("id");
							$("#resultTable").flexToggleCol(id,false);
						}
					});
				}//end of success
			});
}


/*function getResult_role(relation_id, ds_type, ds_id) {
	var data = {};
	data["id"] = relation_id+"";
	data["ds_type"] = ds_type;
	data["ds_id"] = ds_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$("#onloading").dialog("open");
	$.ajax({
		url : "/sview/relationResult",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#onloading").dialog("close");
			$("#role_right").html("");
			var table = $("<table></table>");
			$("#role_right").append(table);
			var array = result["result"];
			var tableTitle = array[0];
			var trhead = $("<tr></tr>");
			table.append(trhead);
			for ( var i = 0; i < tableTitle.length; i++) {
				var column = tableTitle[i];
				var vname = column["vname"];
				var th = $("<th></th>");
				th.text(vname);
				trhead.append(th);
			}
			for ( var i = 1; i < array.length; i++) {
				var trbody = $("<tr></tr>");
				table.append(trbody);
				var item = array[i];
				for ( var j = 0; j < item.length; j++) {
					var ele = item[j];
					var v = ele["v"];
					var name = new String(ele["name"]);
					var content = ele["content"];
					var dis = ele["displayName"];//content;
//					if (name.indexOf("u") == 0) {
//						dis = getLocalname(content);
//					}
					var td = $("<td></td>");
					trbody.append(td);
					td.attr("v", v);
					td.attr("name", name);
					var div = $("<span></span>");
					div.attr("title", content);
					div.text(dis);
					td.append(div);
				}
			}
		}
	});
}*/